package m

import (
	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

type UserSet struct {
	BaseM
	Uid  bson.ObjectId `bson:"_id" json:"uid"`
	Sets string        `bson:"sets" json:"sets"`
}

func NewUserSet() cache.EntryI {
	return &UserSet{}
}

// 保存信息
func (uSet *UserSet) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("userSet", bson.M{"_id": uSet.Uid}, uSet)
	if err != nil {
		return
	}
	return
}

func (uSet *UserSet) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uSet.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uSet.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UserSet_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uSet.LoadData()
}

// 加载数据
func (uSet *UserSet) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("userSet", bson.M{"_id": uSet.Uid}, nil, &uSet)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (uSet *UserSet) Update(val *UserSet) {
	Cache.Put("userSet", uSet.Uid.Hex(), val)
	val.UpdateData()
}

func (u *User) GetUserSets() string {
	v, _ := Cache.Get("userSet", u.Uid.Hex())
	return v.(*UserSet).Sets
}

func (u *User) UpdateUserSet(sets string) {
	v, _ := Cache.Get("userSet", u.Uid.Hex())
	s := v.(*UserSet)
	s.Sets = sets
	s.Update(s)
}
